package com.nanyang.tms.manager.forecast.handler;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionDefinition;

import com.nanyang.common.core.flow.context.AbsTransHandlerContext;
import com.nanyang.common.core.flow.context.TransHandlerContext;
import com.nanyang.common.core.flow.handler.AbstractTransHandler;
import com.nanyang.tms.common.dict.TmsExceptionEnum;
import com.nanyang.tms.common.exception.TmsManagerException;
import com.nanyang.tms.common.util.TmsExceptionUtil;
import com.nanyang.tms.dao.company.CompanyStoredDao;
import com.nanyang.tms.domain.company.CompanyStoredVO;
import com.nanyang.tms.domain.forecast.context.CalculateFreightContext;

import lombok.extern.slf4j.Slf4j;
@Component
@Slf4j
public class FreezeHandler extends AbstractTransHandler{
	@Autowired
	private CompanyStoredDao companyStoredDao;
	@Override
	public boolean isAsync() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean handle(TransHandlerContext context) {
		CalculateFreightContext calculateFreightContext = (CalculateFreightContext) context
				.getInnerContext(CalculateFreightContext.class);
		try {
			CompanyStoredVO companyStored = companyStoredDao.getCompanyStored(calculateFreightContext.getCompanyCode());
			if(companyStored == null){
				throw new TmsManagerException(TmsExceptionEnum.COMPANY_STORE_IS_NOT_EXIST.getCode(), TmsExceptionEnum.COMPANY_STORE_IS_NOT_EXIST.getMessage());
			}
			if(companyStored.getUseBalance().doubleValue()<0){
				throw new TmsManagerException(TmsExceptionEnum.COMPANY_STORE_BALANCE_IS_NOT_ENOUGH.getCode(), TmsExceptionEnum.COMPANY_STORE_BALANCE_IS_NOT_ENOUGH.getMessage());
			}
			boolean result=companyStoredDao.updateFrozenAmount(calculateFreightContext.getCompanyCode(), calculateFreightContext.getAmount());
			if(!result){
				throw new TmsManagerException(TmsExceptionEnum.COMPANY_STORE_BALANCE_IS_NOT_ENOUGH.getCode(), TmsExceptionEnum.COMPANY_STORE_BALANCE_IS_NOT_ENOUGH.getMessage());
			}
			
			
			
		} catch (Exception e) {
			throw TmsExceptionUtil.wrapException(e);
		}
		return true;
	}

}
